var reachlin_annotations = null;

function reachlinAddLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
};	

function reachlinAddEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
};

function reachlinGetCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;    
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
};

function reachlinSetCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
};

function getAnnotationByTag(id) {
	var rtn ="";
	for (var index in reachlin_annotations) {
		if (reachlin_annotations[index].tagid == id) {
			rtn += reachlin_annotations[index].html;
		}
	}
	return rtn;
};

function composeContents(id) {
	var divelement = document.createElement("div");	
	var annotation = getAnnotationByTag(id);
	if (annotation.length>0) {
		divelement.innerHTML = annotation;
	} else {
		// disable because we have refresh button now
		// fetchAnnotation(id, divelement);
		divelement.innerHTML = "<div>Please input your comments...</div>";		
	}
	return divelement;
};

function composeURL(action, id, infunction) {		
	var uri = escape(location.href);	
	var basic = reachlinGetCookie('defaultsite')+'/annotation/'+action+'?tagid='+id+'&uri='+uri;
	// var basic = 'http://localhost/annotation/'+action+'?tagid='+id+'&uri='+uri;
	var rtn = ""
	if (action == "list") {
		rtn = basic;
	} else if (action == "modify") {
		rtn = basic;
	} else if (action == "query") {
		rtn = basic+'&email='+escape(reachlinGetCookie('defaultauthor'));
	}
	// alert(rtn);
	if (infunction) {
		rtn += "&infunction=true";
	}
	return rtn;
};

function getFirstElement(node) {
	for (var index in node.childNodes) {
		if (node.childNodes[index].nodeType == 1) {
			return node.childNodes[index];
		}
	}
	return null;
};

function insertAsFirstElement(child, parent) {
	var inserted = false;
	for (var index in parent.childNodes) {
		if (parent.childNodes[index].nodeType == 1) {
			// insert before the first element
			parent.insertBefore(child, parent.childNodes[index]);
			inserted = true;
			break;
		}
	}
	if (!inserted) {
		// not inserted, either there's no child or non is an element
		parent.appendChild(child);
	}
};

function refreshAnnotation(id, target) {
	var jsondata_tag = document.getElementById("reachlin_jsondata");
	if (jsondata_tag && jsondata_tag.src) {
		//jsondata_tag.src = "http://reachlin.appspot.com/annotation/query?uri="+escape(window.location.href)+"&email=anonymous&infunction=true";
		jsondata_tag.src = composeURL("query", id, "true");
	}
};

function checkTag(target) {	
	// safe guard
	if (!(target&&target.id)) {
		return;
	}
	var firstElement = getFirstElement(target);
	if (target.id.substr(0,8)=="reachlin") {
		// our own tags
		return;
	} else if(firstElement && firstElement.id && firstElement.id.substr(0,8)=="reachlin") {
		// we attached this tag before
		// replace the content used when refreshing
		alert("refresh");
		return;
	}else {
		// attach our html
		var outter = document.createElement("div");		
		outter.id = "reachlin_"+target.id;		
		var openicon = document.createElement("a");
		openicon.href="#";
		// openicon.style.backgroundColor = "#FFFF64";
		// openicon.style.height = "100px";
		// openicon.style.width = "200px";
		reachlinAddEvent(openicon, "click", function(event){
			document.getElementById("reachlin_innerdiv_"+target.id).style.display = "";
		}, true);
		// openicon.innerHTML = "[+]";
		var innerdiv = document.createElement("div");
		innerdiv.style.backgroundColor = "#FFFF64";
		innerdiv.style.border = "3px ridge #FFCC00";
		innerdiv.style.display = "none";
		innerdiv.id = "reachlin_innerdiv_"+target.id;
		
		var contentdiv = composeContents(target.id);
		
		var closeicon = document.createElement("a");
		closeicon.href="#";
		reachlinAddEvent(closeicon, "click", function(event){
			document.getElementById("reachlin_innerdiv_"+target.id).style.display = "none";
		}, true);		
		// closeicon.innerHTML = "[X]";
		closeicon.style.cssFloat = "right";
		
		var newicon = document.createElement("a");
		newicon.href = composeURL("modify", target.id, null);
		newicon.target = "new";
		// newicon.innerHTML = "[+]";
		newicon.style.cssFloat = "right";
		
		var refreshicon = document.createElement("a");
		refreshicon.href = "#";
		reachlinAddEvent(refreshicon, 'click', function(event){
			refreshAnnotation(target.id, contentdiv);
		}, true);
		// refreshicon.innerHTML = "[R]"
		refreshicon.style.cssFloat = "right";
		
		var detailicon = document.createElement("a");
		detailicon.href = composeURL("list", target.id, null);
		detailicon.target = "new";
		// detailicon.innerHTML = "[..]";
		detailicon.style.cssFloat = "right";		
		
		// add icon pictures
		var newiconimg = document.createElement("img");
		newiconimg.src = reachlinGetCookie('defaultsite')+"/visual/24edit.png";
		newiconimg.style.border = "none";
		newiconimg.title = "New";
		newicon.appendChild(newiconimg);
		var closeiconimg = document.createElement("img");
		closeiconimg.src = reachlinGetCookie('defaultsite')+"/visual/24close.png";
		closeiconimg.style.border = "none";
		closeiconimg.title = "Close";
		closeicon.appendChild(closeiconimg);
		var refreshiconimg = document.createElement("img");
		refreshiconimg.src = reachlinGetCookie('defaultsite')+"/visual/24refresh.png";
		refreshiconimg.style.border = "none";
		refreshiconimg.title = "Refresh";
		refreshicon.appendChild(refreshiconimg);
		var detailiconimg = document.createElement("img");
		detailiconimg.src = reachlinGetCookie('defaultsite')+"/visual/24detail.png";
		detailiconimg.style.border = "none";
		detailiconimg.title = "Detail";
		detailicon.appendChild(detailiconimg);
		var openiconimg = document.createElement("img");
		openiconimg.src = reachlinGetCookie('defaultsite')+"/visual/24logo.png";
		openiconimg.style.border = "none";
		openiconimg.title = "Show comments";
		openicon.appendChild(openiconimg);
		var emailinput = document.createElement("input");		
		emailinput.type = "text";
		emailinput.value = reachlinGetCookie("defaultauthor");
		reachlinAddEvent(emailinput, 'change', function(event) {
			if (event && event.target && event.target.value) {
				reachlinSetCookie("defaultauthor", event.target.value, 7);
			}
		},true);
		emailinput.style.cssFloat = "right";	
		emailinput.title = "Fetch comments by an email address...";	
		
		// append tags
		// insert contents				
		innerdiv.appendChild(closeicon);
		innerdiv.appendChild(newicon);		
		innerdiv.appendChild(detailicon);
		innerdiv.appendChild(refreshicon);
		innerdiv.appendChild(emailinput);
		innerdiv.appendChild(contentdiv);				
		outter.appendChild(openicon);
		outter.appendChild(innerdiv);
		insertAsFirstElement(outter, target);
		// target.insertBefore(outter, target.firstChild);
		// target.appendChild(outter);
	}
	// mark the modified area
	// target.style.border = "thin solid green";
};


function renderAnnotations() {	
	for (var index in reachlin_annotations) {
		var anchor = document.getElementById(reachlin_annotations[index].tagid);
		checkTag(anchor);
	}
};
	
function reachlinParseJson(data) {
	// Check the cookies
	alert("reachlinParseJson");
	var email = reachlinGetCookie('defaultauthor');
	if (email == null || email == "") {
		reachlinSetCookie('defaultauthor', 'anonymous', 7);
	}
	var site = reachlinGetCookie('defaultsite');
	if (site == null || site == "") {
		reachlinSetCookie('defaultsite', 'http://reachlin.appspot.com', 7);
	}	
	
	var mybody = document.getElementsByTagName("BODY");
	if (mybody && mybody.length>0 && (!mybody[0].id)) {
		mybody[0].id = "whynotgiveaname";
	}
	if (data.items) {
		reachlin_annotations = data.items;
		renderAnnotations();
	}
	// alert(data.msg);	
};

function windowclick(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;	
	}
	if (targ.nodeType == 3) {
		// defeat Safari bug
	  targ = targ.parentNode;
	}
	var tname;
	tname=targ.tagName;
	// ctrl+left click
	if (!e.ctrlKey || e.button==2) {
		return;
	}
	// put annotation only under tags with an id,
	// or the top body tag 
	var clicked = targ;	
	while(!clicked.id) {
		if (clicked.parentNode) {
			clicked = clicked.parentNode;
		} else {
			// won't happen, should be catch at body
			// which a give name will be there at the worst case
			clicked = null;
			break;
		}
	}
	if (clicked) {
		checkTag(clicked);
	}	
};

var reachlinOnLoad = false;

function reachlinreload() {
	alert("reachlinreload");
	if (reachlinOnLoad) {return;}	
	reachlinOnLoad = true;	
	// fetch annotations for this page
	// the returned object will call reachlinParseJson()
	var jsondata_tag = document.getElementById("reachlin_jsondata");
	if (jsondata_tag && jsondata_tag.src) {
		//jsondata_tag.src = "http://reachlin.appspot.com/annotation/query?uri="+escape(window.location.href)+"&email=anonymous&infunction=true";
		jsondata_tag.src = composeURL("query", "", "true");
	}	
	reachlinOnLoad = false;
};

function reachlinmain() {
	alert("reachlinmain");
	// load annotations
	reachlinreload();	
	// hook up onclick and onload
	reachlinAddEvent(window.document, "click", windowclick, false);
	reachlinAddLoadEvent(reachlinreload);	
}

// document.write('<script type="text\/javascript" src="http:\/\/reachlin.appspot.com\/annotation\/query?tagid=top-stories&uri='+escape(window.location.href)+'&email=anonymous&infunction=true"><\/script>');
// document.write('<div>hello<\/div>');	

